package com.gl.course2;

/**
 * Created by GAOLEI on 2019/7/29.
 */
public class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode node =  new ListNode(0);;
        ListNode curr = node;
        int carry = 0;
        while (l1 !=null || l2 != null){
            int x = l1 != null ? l1.val : 0;
            int y = l2 != null ? l2.val : 0;
            int sum = x + y + carry;
            carry = sum/10;
            int newVal = sum%10;
            curr.next =new ListNode(newVal);
            curr = curr.next;
            if(l1  != null)
                l1 =l1.next;
            if (l2 != null)
                l2 = l2.next;
        }
        if (carry != 0&&node != null){
            curr.next = new ListNode(carry);
        }
        return node.next;
    }

}

class T{
    //(2 -> 4 -> 3) + (5 -> 6 -> 4)  708
    public static void main(String[] args) {
        ListNode node2 = new ListNode(2);
        ListNode node4 = new ListNode(4);
        ListNode node3 = new ListNode(3);

        ListNode node_5 = new ListNode(5);
        ListNode node_6 = new ListNode(6);
        ListNode node_4 = new ListNode(4);

        node2.next = node4;
        node4.next = node3;

        node_5.next = node_6;
        node_6.next = node_4;
        Solution s = new Solution();
        ListNode listNode = s.addTwoNumbers(node2, node_5);
        while (listNode != null){
            System.out.print(listNode.val);
            listNode = listNode.next;
        }

    }
}